package com.haofengsoft.platform.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

/**
 * Created by microwintech on 2015/4/3.
 */
public class FileUtil {
    /**
     * 截取文件路径的最后文件名. 根目录返回 根目录 /, 如果文件名最后是/, 返回空字符串. / --> / /path --> /path
     * /path/1 --> 1 /path/1/ --> ""
     */
    public static String getFileNameByFilePath(String file_path) {
        int index = file_path.lastIndexOf('/');
        if (index == -1 || index == 0)
            return file_path;
        return file_path.substring(index + 1);
    }

    /**
     * * 判断某个文件是否在某个文件夹下 （在）
     */
    public static boolean isExistFileInFolder(File srcDir, String file_name) {
        try {
            if (!srcDir.isDirectory())
                return false;// 判断是否是目录
            File[] srcFiles = srcDir.listFiles();
            for (int i = 0; i < srcFiles.length; i++) {
                if (srcFiles[i].isFile()) {
                    if (file_name.equals(srcFiles[i].getName())) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {

        }
        return false;
    }

    /**
     * * 判断某个文件是否在某个文件夹下(不在)
     */
    public static boolean isNotExistFileInFolder(File srcDir, String file_name) {
        boolean result = isExistFileInFolder(srcDir, file_name) ? false : true;
        return result;
    }

    /**
     * 读取源文件内容
     *
     * @param filename
     *            String 文件路径
     * @return byte[] 文件内容
     * @throws java.io.IOException
     */
    public static byte[] readFile(String filename) {
        File file = new File(filename);
        long len = file.length();
        byte[] bytes = new byte[(int) len];
        BufferedInputStream bufferedInputStream;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
            int r = bufferedInputStream.read(bytes);
            if (r != len) {
                bufferedInputStream.close();
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    public static String getURLByEncode(String result_str) {
        // 初始值
        String[] string_array = result_str.split("\\\\");
        String url_str = "/" + string_array[1];
        for (int j = 2; j < string_array.length; j++) {
            try {
                url_str += "/" + URLEncoder.encode(string_array[j], "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return url_str;
    }

    public static void copyStream(InputStream is, OutputStream os) throws IOException {
        final int buffer_size = 1024;
        byte[] bytes = new byte[buffer_size];
        while (true) {
            int count = is.read(bytes, 0, buffer_size);
            if (count == -1) {
                break;
            }
            os.write(bytes, 0, count);
        }
    }

    /**
     * 启用系统自带的文件下载功能*
     */

    /**
     * 浏览某个文件 *
     */
    public static void openFile(File f, Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type = getFileType(f);
        intent.setDataAndType(Uri.fromFile(f), type);
        context.startActivity(intent);
    }

    public static String getFileType(File f) {
        String end = f.getName().substring(f.getName().lastIndexOf(".") + 1, f.getName().length()).toLowerCase();
        String type = "";
        if (end.equals("mp3") || end.equals("aac") || end.equals("aac") || end.equals("amr") || end.equals("mpeg") || end.equals("mp4")) {
            type = "audio";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg")) {
            type = "image";
        } else {
            type = "*";
        }
        type += "/*";
        return type;
    }

    /**
     * 获取单个文件的MD5值！
     *
     * @param file
     * @return
     */

    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    public static void deleteTempFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }

    public static void deleteTempFileList(List<String> file_list) {
        for (String str : file_list) {
            deleteTempFile(str);
        }
    }

    /**
     * + * 添加到图库//添加到图库,这样可以在手机的图库程序中看到程序拍摄的照片 +
     */
    public static void galleryAddPic(Context context, String path) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(path);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    }
}
